'use client';

import React, { useState, useEffect, useMemo } from 'react';
import {
  ComposedChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  ResponsiveContainer,
  Tooltip,
} from 'recharts';
import { FullscreenIcon, TrendingUpIcon, BarChartIcon } from 'lucide-react';

interface CandleData {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

interface CandleChartProps {
  symbol: string;
}

interface ProcessedCandleData extends CandleData {
  timeStr: string;
  bodyHeight: number;
  bodyTop: number;
  isGreen: boolean;
  wickTop: number;
  wickBottom: number;
}

export default function CandleChart({ symbol }: CandleChartProps) {
  const [timeframe, setTimeframe] = useState('4h');
  const [showIndicators, setShowIndicators] = useState(false);
  const [showVolume, setShowVolume] = useState(true);
  const [candleData, setCandleData] = useState<CandleData[]>([]);

  // 生成模拟K线数据
  useEffect(() => {
    const generateMockData = () => {
      const data: CandleData[] = [];
      let basePrice = 62350;
      const now = Date.now();
      
      for (let i = 100; i >= 0; i--) {
        const time = now - i * 4 * 60 * 60 * 1000; // 4小时间隔
        const open = basePrice + (Math.random() - 0.5) * 1000;
        const volatility = Math.random() * 0.05 + 0.01; // 1-6% 波动
        const range = open * volatility;
        
        const high = open + Math.random() * range;
        const low = open - Math.random() * range;
        const close = low + Math.random() * (high - low);
        const volume = Math.random() * 1000000 + 100000;
        
        data.push({ time, open, high, low, close, volume });
        basePrice = close;
      }
      
      setCandleData(data);
    };

    generateMockData();
    
    // 模拟实时更新
    const interval = setInterval(generateMockData, 5000);
    return () => clearInterval(interval);
  }, [symbol, timeframe]);

  // 处理K线数据
  const processedData = useMemo(() => {
    return candleData.map((candle): ProcessedCandleData => {
      const isGreen = candle.close > candle.open;
      const bodyTop = Math.max(candle.open, candle.close);
      const bodyHeight = Math.abs(candle.close - candle.open);
      
      return {
        ...candle,
        timeStr: new Date(candle.time).toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
        }),
        bodyHeight,
        bodyTop,
        isGreen,
        wickTop: candle.high,
        wickBottom: candle.low,
      };
    });
  }, [candleData]);

  const timeframes = [
    { label: '1m', value: '1m' },
    { label: '15m', value: '15m' },
    { label: '1h', value: '1h' },
    { label: '4h', value: '4h' },
    { label: '1d', value: '1d' },
  ];

  const indicators = ['MACD', 'RSI', 'MA', 'BOLL'];

  // 自定义 Tooltip
  const CustomTooltip = ({ active, payload }: {
    active?: boolean;
    payload?: Array<{
      payload: ProcessedCandleData;
    }>;
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      
      return (
        <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-3">
          <p className="font-medium text-gray-900 dark:text-white mb-2">
            {new Date(data.time).toLocaleString('zh-CN')}
          </p>
          <div className="grid grid-cols-2 gap-2 text-sm">
            <div>
              <span className="text-gray-500 dark:text-gray-400">开盘: </span>
              <span className="text-gray-900 dark:text-white">${data.open.toFixed(2)}</span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">最高: </span>
              <span className="text-green-600 dark:text-green-400">${data.high.toFixed(2)}</span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">最低: </span>
              <span className="text-red-600 dark:text-red-400">${data.low.toFixed(2)}</span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">收盘: </span>
              <span className={data.isGreen ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}>
                ${data.close.toFixed(2)}
              </span>
            </div>
          </div>
          <div className="mt-2 text-sm">
            <span className="text-gray-500 dark:text-gray-400">成交量: </span>
            <span className="text-gray-900 dark:text-white">
              {(data.volume / 1000).toFixed(0)}K
            </span>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 h-full flex flex-col">
      {/* 工具栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-4">
          {/* 时间周期选择 */}
          <div className="flex items-center space-x-1">
            {timeframes.map((tf) => (
              <button
                key={tf.value}
                onClick={() => setTimeframe(tf.value)}
                className={`px-3 py-1 text-sm rounded-md transition-colors ${
                  timeframe === tf.value
                    ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
                    : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
                }`}
              >
                {tf.label}
              </button>
            ))}
          </div>

          {/* 技术指标 */}
          <div className="relative">
            <button
              onClick={() => setShowIndicators(!showIndicators)}
              className="flex items-center space-x-1 px-3 py-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
            >
              <TrendingUpIcon className="w-4 h-4" />
              <span>指标</span>
            </button>

            {showIndicators && (
              <div className="absolute top-full left-0 mt-1 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-20 p-2">
                {indicators.map((indicator) => (
                  <button
                    key={indicator}
                    className="block w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-md"
                  >
                    {indicator}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* 成交量开关 */}
          <button
            onClick={() => setShowVolume(!showVolume)}
            className={`px-3 py-1 text-sm rounded-md transition-colors ${
              showVolume
                ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
            }`}
          >
            成交量
          </button>
        </div>

        <div className="flex items-center space-x-2">
          <button className="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors">
            <BarChartIcon className="w-4 h-4" />
          </button>
          <button className="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors">
            <FullscreenIcon className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="flex-1 p-4">
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart data={processedData} margin={{ top: 10, right: 10, left: 10, bottom: 10 }}>
            <XAxis
              dataKey="timeStr"
              tick={{ fontSize: 11, fill: '#6B7280' }}
              stroke="#9CA3AF"
              interval="preserveStartEnd"
            />
            <YAxis
              domain={['dataMin - 100', 'dataMax + 100']}
              tick={{ fontSize: 11, fill: '#6B7280' }}
              stroke="#9CA3AF"
              tickFormatter={(value) => `$${value.toFixed(0)}`}
            />
            
            <Tooltip content={<CustomTooltip />} />
            
            {/* 价格线（简化的K线表示） */}
            <Line
              type="monotone"
              dataKey="close"
              stroke="#3B82F6"
              strokeWidth={1}
              dot={false}
              connectNulls={false}
            />
            
            {/* 成交量柱状图 */}
            {showVolume && (
              <Bar
                dataKey="volume"
                fill="#94A3B8"
                fillOpacity={0.3}
                yAxisId="volume"
              />
            )}
            
            {/* 添加一个额外的Y轴用于成交量 */}
            {showVolume && (
              <YAxis
                yAxisId="volume"
                orientation="right"
                tick={{ fontSize: 11, fill: '#6B7280' }}
                stroke="#9CA3B8"
                tickFormatter={(value) => `${(value / 1000).toFixed(0)}K`}
              />
            )}
          </ComposedChart>
        </ResponsiveContainer>
      </div>

      {/* 点击外部关闭指标选择器 */}
      {showIndicators && (
        <div
          className="fixed inset-0 z-10"
          onClick={() => setShowIndicators(false)}
        />
      )}
    </div>
  );
}
